<template>
  <el-dialog :title="formData.goodsId?'修改信息':'添加信息'" :visible.sync="visible">
    <el-form :model="formData" :rules="rules" label-width="80px" ref="dataDom">
      <el-form-item label="商品名" prop="name">
        <el-input v-model="formData.name" placeholder="商品名"/>
      </el-form-item>
      <el-form-item label="进价" prop="getPrice">
        <el-input v-model="formData.getPrice" placeholder="进价"/>
      </el-form-item>
      <el-form-item label="售价" prop="salePrice">
        <el-input v-model="formData.salePrice" placeholder="售价"/>
      </el-form-item>
      <el-form-item label="进货数量" prop="goodsNum">
        <el-input v-model="formData.goodsNum" placeholder="进货数量"/>
      </el-form-item>
      <el-form-item label="进货人" prop="getMan">
        <el-input v-model="formData.getMan" placeholder="进货人"/>
      </el-form-item>
      <el-form-item label="规格" prop="prospecId">
        <el-select v-model="formData.prospecId" clearable placeholder="请选择规格">
          <el-option v-for="item in proSpecList" :key="item.prospecId" :label="item.goodsPack" :value="item.prospecId"/>
        </el-select>
        <el-popover
          placement="right"
          width="280"
          trigger="hover">
          <el-input v-model="goodsPack" placeholder="请输入新增规格的名字" style="width: 200px;margin-right: 10px"></el-input>
          <el-button type="primary" @click="addPropesc">提交</el-button>
          <a href="javascript:;" slot="reference" style="margin-left: 15px;font-size: 13px">规格不符？试着悬浮新增</a>
        </el-popover>
      </el-form-item>
      <el-form-item label="展示柜" prop="cabinetId">
        <el-select v-model="shopId" filterable placeholder="请选择商铺" clearable @change="getAllCabinet" style="width: 300px">
          <el-option v-for="(item,index) in allShopList" :key="index" :label="item.address+'/'+item.shopName" :value="item.shopId">
          </el-option>
        </el-select>
        <el-select v-model="formData.cabinetId" filterable placeholder="请选择货架" clearable>
          <el-option v-for="(item,index) in allCabinetList" :key="index" :label="item.number" :value="item.cabinetId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="typeIds">
        <el-select v-model="formData.typeIds" clearable filterable multiple placeholder="请选择类型">
          <el-option v-for="item in typeList" :key="item.typeId" :label="item.name" :value="item.typeId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="进货日期" prop="goodsTime">
        <el-date-picker v-model="formData.goodsTime" type="date" value-format="yyyy-MM-dd" placeholder="选择进货日期"/>
      </el-form-item>
      <el-form-item label="照片列表">
        <el-upload :action="uploadUrl" :headers="uploadHeader" :list-type="'picture-card'" :before-upload="beforeUpload" :on-success="uploadSuccess" :file-list="imageList" ref="imageListRef">
          <i class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img :src="file.url" alt="" class="el-upload-list__item-thumbnail">
            <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="showImageDetail(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          class="el-upload-list__item-delete"
          @click="removeImage(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="imageListDialogVisible" append-to-body>
          <img :src="imageListDialogImgSrc" alt="" height="100%" width="100%">
        </el-dialog>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">启用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" @click="submitInfo">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const initInfo = {
  goodsId: '',
  name: '',
  getPrice: '',
  salePrice: '',
  goodsNum: '',
  getMan: '',
  prospecId: '',
  cabinetId: '',
  goodsTime: '',
  status: 1,
  imageUrls: [],
  typeIds: []
}
export default {
  data () {
    return {
      visible: false,
      formData: {
        ...initInfo
      },
      rules: {
        name: [
          { required: true, message: '商品名不能为空', trigger: 'blur' }
        ],
        getPrice: [
          { required: true, message: '进货价格不能为空', trigger: 'blur' }
        ],
        salePrice: [
          { required: true, message: '销售价格不能为空', trigger: 'blur' }
        ],
        goodsNum: [
          { required: true, message: '进货数量不能为空', trigger: 'blur' }
        ],
        getMan: [
          { required: true, message: '进货人不能为空', trigger: 'blur' }
        ],
        goodsTime: [
          { required: true, message: '进货时间不能为空', trigger: 'blur' }
        ],
        typeIds: [
          { required: true, message: '请选择商品的分类', trigger: 'blur' }
        ],
        prospecId: [
          { required: true, message: '请选择商品的规格', trigger: 'blur' }
        ],
        cabinetId: [
          { required: true, message: '请选择展示柜', trigger: 'blur' }
        ]
      },
      loading: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/upload',
      baseImageUrl: process.env.VUE_APP_BASE_API + '/img/',
      uploadHeader: {
        token: ''
      },
      dialogVisible: false,
      dialogImgSrc: '',
      imageList: [], /* 存储上传文件的显示地址 ，真正上传用formData.imageUrls */
      imageListDialogVisible: false,
      imageListDialogImgSrc: '',
      typeList: [], /* 展示下拉框用的list,上传用typeIds */
      proSpecList: [], /* 展示规格下拉框用的list,上传用formData.prospecId */
      shopId: '', /* 作为联动查询展示柜的字段 */
      allShopList: [], /* 查询出所有的店铺 */
      allCabinetList: [], /* 查询出的展示柜 */
      goodsPack: '', /* 新增的（规格）名字 */
      showPopover: false/* 提示框的显示 */
    }
  },
  methods: {
    init (goodsId) {
      this.imageList = []
      /* 开启弹窗 */
      this.visible = true
      this.formData = { ...initInfo }

      /* 获取规格下拉框 */
      this.$http.get('/goods/spec/list').then(data => {
        if (data.code === 0) {
          this.proSpecList = data.list
        }
      })
      /* 获取分类下拉框 */
      this.$http.get('/goods/type/list').then(data => {
        if (data.code === 0) {
          this.typeList = data.list
        }
      })
      /* 判断userId是否有值 */
      if (goodsId) {
        /* 成立表示该次操作为修改，发送ajax请求获取信息 */
        this.$http.get('/goods/info/' + goodsId).then(data => {
          if (data.code === 0) {
            this.formData = { /* formdata接收所有data里的数据包括有的和没有的（imageList和typeList） */
              ...data.data
            }
            /* 根据cabinetId查出shopId，如果不查，修改的时候就无法显示两个select框选择的值 */
            this.$http.get('/goods/message/' + this.formData.cabinetId).then(data => {
              if (data.code === 0) {
                this.shopId = parseInt(data.message.split('-')[3])/* 查出shopId */
                const cabinetId = this.formData.cabinetId
                this.getAllCabinet()/* 根据shopId查出货架 */
                /* 如果要更换shop那么查货架的时候需要清空cabinetlist以及cabinetId
                 这里提前保管被清空的cabinet值，正常显示结果，同时防止了切换shop时不删除对应的cabinetlist以及cabinetId情况 */
                this.formData.cabinetId = cabinetId
              }
            })
            /* 处理多张图片数据 */
            if (this.imageList.length > 0) {
              this.imageList.length = 0
            }
            this.imageList = this.formData.imageList.map(item => {
              return {
                name: item.imageUrl,
                url: this.baseImageUrl + item.imageUrl
              }
            })
            /* 处理提交的表单中的imageUrls */
            this.formData.imageUrls = this.formData.imageList.map(item => item.imageUrl)
            /* 处理提交的表单中的分类Id */
            this.formData.typeIds = this.formData.typeList.map(item => item.typeId)
          } else {
            this.$message.error('数据加载失败，请重试！')
          }
        })
      }
    },
    submitInfo () {
      this.$refs.dataDom.validate(valid => {
        if (valid) {
          this.loading = this.$loading({ text: '加载中...' })
          this.$http.post('/goods/update', this.formData).then(data => {
            // console.log(this.formData)
            this.loading.close()
            if (data.code === 0) {
              this.$message({
                message: `${!this.formData.goodsId ? '添加' : '修改'}成功`,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('onCloseWin')
                }
              })
            } else {
              this.$alert('操作失败', { type: 'error' })
            }
          })
        }
      })
    },
    beforeUpload (file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isImg) {
        this.$message.error('文件格式不正确！')
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('文件大小不能超过5M')
      }
      return isImg && isLt5M
    },
    uploadSuccess (res) {
      if (res.code === 0) {
        this.formData.imageUrls.push(res.data) /* 用于上传 */
        this.imageList = this.formData.imageUrls.map(item => { /* 用于显示 */
          return {
            url: this.baseImageUrl + item,
            name: item
          }
        })
      }
    },
    handlePictureCardPreview (file) {
      this.dialogVisible = true
      this.dialogImgSrc = file.url
    },
    showImageDetail (file) {
      this.imageListDialogVisible = true
      this.imageListDialogImgSrc = file.url
    },
    handleRemove (file) {
      this.$confirm('确定删除该图片吗？').then(() => {
        this.formData.cover = ''
        this.$refs.uploadImage.handleRemove(file)
      })
    },
    removeImage (file) {
      this.$confirm('确定删除该图片吗？').then(() => {
        this.$refs.imageListRef.handleRemove(file)
        for (let i = 0; i < this.formData.imageUrls.length; i++) {
          if (this.formData.imageUrls[i] === file.name) {
            this.formData.imageUrls.splice(i, 1)
          }
        }
      })
    },
    getAllShop () {
      this.$http.get('/goods/cascade/allshop').then(data => {
        if (data.code === 0) {
          this.allShopList = data.list
        }
      })
    },
    getAllCabinet () {
      this.allCabinetList = []
      this.formData.cabinetId = ''
      this.$http.get('/goods/cascade/mycabinet/' + this.shopId).then(data => {
        if (data.code === 0) {
          this.allCabinetList = data.list
        }
      })
    },
    addPropesc () { /* 增加规格 */
      this.loading = this.$loading({ text: '加载中...' })
      this.$http.post('/goods/add/prospec', {
        goodsPack: this.goodsPack
      }).then(data => {
        this.loading.close()
        if (data.code === 0) {
          /* 重新获取规格下拉框 */
          this.$http.get('/goods/spec/list').then(data => {
            if (data.code === 0) {
              this.proSpecList = data.list
            }
          })
          this.goodsPack = ''
          this.$message({
            message: '增加成功!',
            type: 'success',
            duration: 500
          })
        }
      })
    }
  },
  created () {
    this.uploadHeader.token = this.$cookies.get('token')
    this.getAllShop()
  }
}
</script>

<style scoped>

</style>
